import dayjs from 'dayjs';
import { IStream, StreamAdd } from './interface';
import { appendToken } from '../utils/index';

export const validateAms = (status: string) => {
	const amsStatus = ['reconnect_failed', 'reconnecting', 'offline'];
	return amsStatus.indexOf(status) === -1;
};

/**
 * 判断当前技能组下，坐席是不是班组长
 */
export const isChiefInGroupId = (groups: number[], serviceId: number | string) => {
	let isChief = false;
	groups.forEach(item => {
		if (item == serviceId) {
			isChief = true;
		}
	});
	return isChief;
};

/** 筛选成员加入会话数据 */
export const filterMembers = (members: any[]): any[] => {
	let result = [];
	result = members.map((item: any) => {
		return {
			id: item.id,
			role: item.role,
			status: item.status ? item.status : 'noraml',
			type: item.type || '',
			clientInfo: item.clientInfo || undefined,
			user: {
				id: item.user.id,
				name: item.user.name,
				org: item.user.org,
				customerLevel: item.user.customerLevel || null,
				profile: getUserProfile(item.user.profile)
			}
		};
	});
	return result;
};

/** 筛选用户数据 */
export const getUserProfile = (profile: { gender?: string | undefined | null; picture?: string | undefined | null; fullName?: string | undefined | null; isRobot?: boolean | null }) => {
	if (!profile || typeof profile !== 'object') return { gender: '', picture: '', fullName: '', isRobot: false };
	return {
		gender: profile.gender || '',
		picture: profile.picture || '',
		fullName: profile.fullName || '',
		isRobot: profile.isRobot || false
	};
};

export const memberJoinSession = (member: any) => {
	const cloneMember = { ...member };
	return {
		id: cloneMember.id,
		role: cloneMember.role,
		status: cloneMember.status ? cloneMember.status : 'noraml',
		type: cloneMember.type || '',
		clientInfo: cloneMember.clientInfo || undefined,
		user: {
			id: cloneMember.user.id,
			name: cloneMember.user.name,
			org: cloneMember.user.org,
			customerLevel: cloneMember.user.customerLevel || null,
			profile: getUserProfile(cloneMember.user.profile)
		}
	};
};

/** 是否是 TTS 标签 */
export const isTTSstream = (streamInfo: any) => {
	const { label = '', audioOnly = false } = streamInfo;
	return label.indexOf('tts') > -1;
};

/** 是否是 录制流 标签 */
export const isRecordHiddenScreenStream = (streamInfo: any) => {
	const { label = '', audioOnly = false } = streamInfo;
	return label.indexOf('recordScreen') > -1 || label.indexOf('recordScreen-Regional') > -1;
};

/** 是否是 语音流 标签 */
export const isAudioStream = (streamInfo: any) => {
	const { label = '', audioOnly = false } = streamInfo;
	return label.indexOf('customer') === -1 && label.indexOf('agent') === -1 && audioOnly === true;
};

/** 是否是 访客流 标签 */
export const isCustomerStream = (streamInfo: any) => {
	const { label = '', audioOnly = false } = streamInfo;
	return label.indexOf('customer') > -1;
};

/** 是否是 坐席流 标签 */
export const isAgentStream = (streamInfo: any) => {
	const { label = '', audioOnly = false } = streamInfo;
	return label.indexOf('agent') > -1;
};

/** 是否是 屏幕共享流 标签 */
export const isScreenStream = (streamInfo: any) => {
	const { label = '', audioOnly = false } = streamInfo;
	return label.indexOf('screen') > -1;
};

/**
 * 压缩图片
 * @param file 压缩文件
 * @param compressThreshold 开启压缩的阈值，默认 5M
 * @param openCompress 是否开启压缩，默认 true
 * @param pictureQuality 压缩比，默认 0.92
 * @returns
 */
export const compressFile = (file: File, compressThreshold = 5, openCompress = true, pictureQuality = 0.92, maxWidth = 480, maxHeight = 320) => {
	//判断是否是图片类型
	const isAccept = ['image/png', 'image/jpeg', 'image/jpg', 'image/gif'].includes(file.type);
	if (isAccept) {
		const fileSize = file.size / 1024 / 1024;
		console.log('before compress, the file size is : ', fileSize.toFixed(2) + ' M');
		//当开启图片压缩且图片大小大于等于压缩阈值,进行压缩
		if (fileSize >= compressThreshold && openCompress) {
			//判断浏览器内核是否支持base64图片压缩
			if (typeof FileReader === 'undefined') {
				return file;
			} else {
				try {
					return new Promise(resolve => {
						//声明FileReader文件读取对象
						const reader = new FileReader();
						reader.readAsDataURL(file);
						reader.onload = () => {
							// 生成canvas画布
							const canvas = document.createElement('canvas');
							// 生成img
							// const img = document.createElement('img');
							const img = new Image();
							img.src = reader.result as any;
							img.onload = () => {
								const ctx = canvas.getContext('2d');
								//原始图片宽度、高度
								const originImageWidth = img.width,
									originImageHeight = img.height;
								//默认最大尺度的尺寸限制在（1920 * 1080）
								const ratio = maxWidth / maxHeight;
								//目标尺寸
								let targetWidth = originImageWidth,
									targetHeight = originImageHeight;
								//当图片的宽度或者高度大于指定的最大宽度或者最大高度时,进行缩放图片
								if (originImageWidth > maxWidth || originImageHeight > maxHeight) {
									//超过最大宽高比例
									if (originImageWidth / originImageHeight > ratio) {
										//宽度取最大宽度值maxWidth,缩放高度
										targetWidth = maxWidth;
										targetHeight = Math.round(maxWidth * (originImageHeight / originImageWidth));
									} else {
										//高度取最大高度值maxHeight,缩放宽度
										targetHeight = maxHeight;
										targetWidth = Math.round(maxHeight * (originImageWidth / originImageHeight));
									}
								}
								// canvas对图片进行缩放
								canvas.width = targetWidth;
								canvas.height = targetHeight;
								// 清除画布
								ctx?.clearRect(0, 0, targetWidth, targetHeight);
								// 绘制图片
								ctx?.drawImage(img, 0, 0, targetWidth, targetHeight);
								// quality值越小,图像越模糊,默认图片质量为0.92
								const imageDataURL = canvas.toDataURL(file.type || 'image/jpeg', pictureQuality);
								// 去掉URL的头,并转换为byte
								const imageBytes = window.atob(imageDataURL.split(',')[1]);
								// 处理异常,将ascii码小于0的转换为大于0
								const arrayBuffer = new ArrayBuffer(imageBytes.length);
								const uint8Array = new Uint8Array(arrayBuffer);
								for (let i = 0; i < imageBytes.length; i++) {
									uint8Array[i] = imageBytes.charCodeAt(i);
								}
								const mimeType = imageDataURL?.split(',')?.[0]?.match(/:(.*?);/)?.[1];
								const newFile = new File([uint8Array], file.name, {
									type: mimeType || 'image/jpeg'
								});
								console.log('after compress, the file size is : ', (newFile.size / 1024 / 1024).toFixed(2) + 'M');
								console.log('after compress file: ', newFile);
								resolve(newFile);
							};
						};
						reader.onerror = () => {
							return file;
						};
					})
						.then(res => {
							return res;
						})
						.catch(() => {
							return file;
						});
				} catch (e) {
					//压缩出错,直接返回原file对象
					return file;
				}
			}
		} else {
			//不需要压缩，直接返回原file对象
			return file;
		}
	} else {
		//非图片文件,不进行压缩,直接返回原file对象
		return file;
	}
};

export const validateImage = async (file: File, maxSize = 20) => {
	//判断是否是图片类型
	const isAccept = ['image/png', 'image/jpeg', 'image/jpg', 'image/gif'].includes(file.type);
	if (!isAccept) return { code: 501, message: `file type ${file.type} is not support`, data: file };
	const fileSize = file.size / 1024 / 1024;
	if (fileSize > maxSize) return { code: 502, message: `file size ${fileSize} is not support`, data: file };
	const { width, height } = await fileToImgSrc(file);
	console.log(width, height);

	if (width > 4096) return { code: 503, message: `file width ${width} is not support`, data: file };
	if (height > 4096) return { code: 504, message: `file height ${height} is not support`, data: file };
	return { code: 200, message: 'ok', data: file };
};

/** 检查图片尺寸 */
export const fileToImgSrc = (file: File): Promise<{ width: number; height: number }> => {
	return new Promise((resolve, reject) => {
		const reader = new FileReader();
		reader.readAsDataURL(file);
		reader.onload = () => {
			const src = reader.result as string;
			let image = new Image();
			image.src = src;
			image.onload = function () {
				resolve({ width: image.width, height: image.height });
			};
		};
	});
};

/** 过滤背景列表数据 */
export const filterBackgroundList = (list: any[]) => {
	return list
		.map(item => {
			return {
				id: item.id || -1,
				url: item.url ? appendToken(item.url) : '',
				abbreviatedUrl: item.abbreviatedUrl ? appendToken(item.abbreviatedUrl) : '',
				type: item.type,
				fileName: item.fileName || '',
				isDefault: item.isDefault || false,
				api: '',
				apiClear: '',
				createdAt: item.createdAt
			};
		})
		.sort((a, b) => {
			// @ts-ignore
			return new Date(a.createdAt) - new Date(b.createdAt);
		});
};

/** 过滤水印列表数据 */
export const filterWaterMarkList = (list: any[]) => {
	return list
		.map(item => {
			return {
				id: item.id || -1,
				url: item.url ? appendToken(item.url) : '',
				position: 1,
				abbreviatedUrl: item.abbreviatedUrl ? appendToken(item.abbreviatedUrl) : '',
				type: item.type ? item.type : 'normal',
				fileName: item.fileName || '',
				isDefault: item.isDefault || false,
				api: '',
				apiClear: '',
				createdAt: item.createdAt
			};
		})
		.sort((a, b) => {
			// @ts-ignore
			return new Date(a.createdAt) - new Date(b.createdAt);
		});
};

/** 校验数组长度 */
export const validateArrayLength = (list: any[], len: number) => {
	return list.length < len;
};

export const filterStreamInfo = (streamData: StreamAdd): IStream => {
	const { data } = streamData;
	console.log('filterStreamInfo:', streamData);
	
	let streamLabel = data.streamLabel;
	let audioOnly = data.audioOnly || false;
	let isAudioMute = data.isAudioMute || false;
	let isVideoMute = data.isVideoMute || false;
	let clientId = data.userInfo?.clientId || data.userInfo?.from?.clientId || data.id;
	let videoId = streamLabel;
	let id = data.id;
	let role = data.userInfo.role || '';
	let customerRole = data.userInfo.customerRole || '';
	let userName = data.userInfo.userName || '';
	return {
		id,
		label: streamLabel,
		audioOnly: audioOnly,
		clientId,
		videoId,
		role,
		isAudioMute,
		isVideoMute,
		muteStatus: false,
		streamMode: audioOnly ? 'audio' : 'video',
		customerRole,
		isScreenSyncMode: false,
		userName,
		networkStatus: '',
		isRobot: id === streamLabel,
	};
};
/**
 * url 转  base64
 * @param url
 * @param callback
 * @param errorCallback
 */
export const urlToBase64 = (url: string) => {
	return new Promise((resolve, reject) => {
		// 创建一个Image对象
		let img = new Image();
		img.crossOrigin = ''; // 如果需要跨域访问，设置crossOrigin为空字符串
		// 当图片加载完成或者发生错误时
		img.onload = function () {
			if (img.complete && img.naturalWidth === 0) {
				// 如果图片自然宽度为0，认为图片加载失败
				// errorCallback('Image load failed: the image is empty or broken.');
                reject('Image load failed: the image is empty or broken.');
				return;
			}
			// 正常加载完成的处理逻辑
			var canvas = document.createElement('canvas');
			canvas.width = img.width;
			canvas.height = img.height;
			var ctx = canvas.getContext('2d');
			ctx!.drawImage(img, 0, 0);
			var base64 = canvas.toDataURL('image/png');
             // 查找最后一个逗号的位置
            const commaIndex = base64.lastIndexOf(',');
            // 如果找到了逗号，返回逗号后的部分，否则返回原始字符串
            let res = commaIndex !== -1 ? base64.substring(commaIndex + 1) : base64;
            resolve(res);
			img = null!;
		};
		img.onerror = () => {
			// 图片加载失败时的回调
			// errorCallback('Image load failed: could not load the image.');
            reject('Image load failed: could not load the image.');
			img = null!;
		};
		// 设置图片的src属性为指定的URL
		img.src = url;
	});
};
